

package ro.ase.catalog.security.dao.hibernate;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import ro.ase.catalog.beans.Authority;
import ro.ase.catalog.dao.hibernate.GenericDAOImpl;
import ro.ase.catalog.security.dao.IAuthorityDAO;

import java.util.List;


public class AuthorityDAOImpl extends GenericDAOImpl<Authority, Integer> implements IAuthorityDAO {

    @SuppressWarnings("unchecked")
    public List<Authority> findByType(String type) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Authority.class);
        criteria.add(Expression.eq("type", type));
        criteria.addOrder(Order.desc("value"));
        return getHibernateTemplate().findByCriteria(criteria);
    }	
    
    public Integer findByNameVagueCount(String name) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Authority.class);
        criteria.add(Expression.like("name", "%" + name + "%"));
        criteria.setProjection(Projections.rowCount());
        return (Integer)getHibernateTemplate().findByCriteria(criteria).get(0);
    }

    @SuppressWarnings("unchecked")
    public List<Authority> findByNameVaguePerPage(String name, int start, int limit) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Authority.class);
        criteria.add(Expression.like("name", "%" + name + "%"));
        return getHibernateTemplate().findByCriteria(criteria, start, limit);
    }  
    
    @SuppressWarnings("unchecked")
    public List<Authority> findByRoleIdPerPage(int roleId, int start, int limit) {
        DetachedCriteria criteria = 
            DetachedCriteria.forClass(Authority.class)
                             .createCriteria("roles","r")
                             .add(Expression.eq("r.id",roleId));
        
        return getHibernateTemplate().findByCriteria(criteria,start,limit);
    }

    @SuppressWarnings("unchecked")
    public List<Authority> findByRoleId(int roleId) {
        DetachedCriteria criteria = 
            DetachedCriteria.forClass(Authority.class)
                             .createCriteria("roles","r")
                             .add(Expression.eq("r.id",roleId));
        
        return getHibernateTemplate().findByCriteria(criteria);
    }
    
    public Integer findByRoleIdCount(int roleId) {
        DetachedCriteria criteria = 
            DetachedCriteria.forClass(Authority.class)
                            .setProjection(Projections.rowCount())
                            .createCriteria("roles")
                            .add(Expression.eq("id",roleId));
        
        return (Integer)getHibernateTemplate().findByCriteria(criteria).get(0);
    }    
}
